package com.zxl.demo;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/31 12:38
 * 下载图片
 */
@WebServlet(name = "DownServlet",value = "/DownServlet")
public class DownServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得下载路径
        String path = "D:\\JSP\\workspace\\study\\Web\\src\\main\\resources\\down.jpg";
        System.out.println(path);
        //获得下载的文件名
        String filename = path.substring(path.lastIndexOf("\\") + 1);
        System.out.println(filename);
        //设置响应头
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));
        //获得下载输入流
        FileInputStream fileInputStream = new FileInputStream(path);
        //创建输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        //创建缓冲区
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len=bytes.length)!=-1){
            outputStream.write(bytes,0,len);
        }
        //释放资源
        outputStream.close();
        fileInputStream.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
